package org.sgtools.gwt.delegate.resolver;

import java.util.Map;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.sgtools.gwt.delegate.ServiceResolver;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;

/**
 * 
 * 
 * @author Semyon Goryachkin
 *
 */
public class SmartServiceResolver implements ServiceResolver, ApplicationContextAware, InitializingBean{
	
	private ApplicationContext applicationContext;
	
	private Map<String, Object> beans = null; 

	private Pattern urlPattern = Pattern.compile("(.gwt)");

	public void setUrlPattern(String urlPattern) {
		this.urlPattern = Pattern.compile(urlPattern);
	}

	
	@Override
	public RemoteService getService(HttpServletRequest request) {
		String serviceName = getServiceName(request.getRequestURI()); 
		Object service = applicationContext.getBean(serviceName);
		if (service == null){
			throw new IllegalStateException("Service " + serviceName + " is not found in context");
		}
		if (!(service instanceof RemoteService)){
			throw new IllegalStateException("Service " + serviceName + " is not com.google.gwt.user.client.rpc.RemoteService");
		}
		return (RemoteService) service;
	}
	
	
	private String getServiceName(String url){
		String serviceName = urlPattern.matcher(url).group();
		return serviceName;
	}
	
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}


	@Override
	public void afterPropertiesSet() throws Exception {
		beans = applicationContext.getBeansWithAnnotation(RemoteServiceRelativePath.class);
	}

}
